<?php

class ErrorController extends Custom_Controller_Action
{
	private $_is_api_request = false;
	private $_requested_method = '';

	public function init()
    {
        /* Initialize action controller here */
		
    }

	public function preDispatch()
	{
		$params = $this->getRequest()->getParams();

		if($params['module'] == 'api')
		{
			$this->_helper->layout()->disableLayout();
			$this->_helper->viewRenderer->setNoRender(true);
			$this->_is_api_request = true;
			$this->_requested_method = $params['controller'].DS.$params['action'];
		}
	}

    public function errorAction()
    {
        $errors = $this->_getParam('error_handler');
        
        if (!$errors) {
            $this->view->message = 'You have reached the error page';
            return;
        }
        
        switch ($errors->type) {
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
        
                // 404 error -- controller or action not found
                $this->getResponse()->setHttpResponseCode(404);
                $this->view->message = 'Page not found';
                break;
            default:
                // application error
                $this->getResponse()->setHttpResponseCode(500);
                $this->view->message = 'Application error';
                break;
        }
        
        // Log exception, if logger available
        if ($log = $this->getLog()) {
            $log->crit($this->view->message, $errors->exception);
        }
        
        // conditionally display exceptions
        if ($this->getInvokeArg('displayExceptions') == true) {
            $this->view->exception = $errors->exception;
        }
        
        $this->view->request   = $errors->request;

		#for api request
		if($this->_is_api_request)
		{
			$api		= new Api_Model_Api();
			$response	= $api->getApiResponse($this->_requested_method, false, '', $this->view->message);
			echo $response;
		}
    }

    public function getLog()
    {
        $bootstrap = $this->getInvokeArg('bootstrap');
        if (!$bootstrap->hasResource('Log')) {
            return false;
        }
        $log = $bootstrap->getResource('Log');
        return $log;
    }

	//api access error
	public function accessAction()
	{
		
	}


}

